package com.krtech.wecard.utils.file;

import com.krtech.wecard.framework.model.CommRes;
import com.krtech.wecard.framework.security.Inner;
import com.krtech.wecard.framework.utils.LoginUtil;
import com.krtech.wecard.module.sys.entity.SysUser;
import com.krtech.wecard.module.sys.service.SysUserService;
import com.krtech.wecard.utils.DfsUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

@RestController
@RequestMapping("/upload")
@Api(value = "文件管理",tags = "文件管理")
public class UploadController {

    private static String URL = "https://seemax.cc";

    @Autowired
    SysUserService sysUserService;

    @RequestMapping("/uploadImage")
    @ApiOperation(value = "上传图片")
    @Inner(value = false)
    public CommRes uploadImage(MultipartFile file, HttpServletRequest request)throws Exception{
        DfsUtil dfsUtil = new DfsUtil();
        File toFile = toFile(file);
        DfsUtil.DfsFile upload = dfsUtil.upload(toFile);
        return CommRes.ok(URL + upload.getSrc());
    }

    @PostMapping("/updateAvatarAndNickName")
    @ApiOperation(value = "更新用户昵称和头像")
    public SysUser updateAvatarAndNickName(@RequestBody SysUser updateUserInfo){
        SysUser userInfo = LoginUtil.getUserInfo();

        SysUser sysUser = sysUserService.getById(userInfo.getUserId());
        sysUser.setAvatar(updateUserInfo.getAvatar());
        sysUser.setNickName(updateUserInfo.getNickName());
        sysUserService.updateById(sysUser);
        return sysUser;
    }

    public File toFile(MultipartFile multipartFile){
        //文件上传前的名称
        String fileName = multipartFile.getOriginalFilename();
        File file = new File(fileName);
        OutputStream out = null;
        try{
            //获取文件流，以文件流的方式输出到新文件
//    InputStream in = multipartFile.getInputStream();
            out = new FileOutputStream(file);
            byte[] ss = multipartFile.getBytes();
            for(int i = 0; i < ss.length; i++){
                out.write(ss[i]);
            }
        }catch(IOException e){
            e.printStackTrace();
        }finally {
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }
}
